﻿#include "opencv_raw.h"

opencv_raw::opencv_raw(QWidget* parent)
	: QWidget(parent)
{
	ui.setupUi(this);

	thread = new QThread(this);         // 创建线程
	raw = new raw_thread();             // 创建线程对象
	raw->moveToThread(thread);          // 将线程对象移动到线程中
	thread->start();                    // 启动线程

	connect(raw, &raw_thread::send_image, this, &opencv_raw::read_image);
	connect(this, &opencv_raw::send_raw_5files, raw, &raw_thread::read_raw_5files);

	// 多帧平均按钮
	connect(ui.pushButton_3, &QPushButton::clicked, [this]() {
		QString folderPath = QFileDialog::getExistingDirectory(this, "选择包含5张RAW的文件夹", QDir::currentPath());
		if (folderPath.isEmpty()) return;

		QDir dir(folderPath);
		QStringList filters;
		filters << "*.raw";
		QFileInfoList fileInfoList = dir.entryInfoList(filters, QDir::Files);

		if (fileInfoList.size() < 5) {
			QMessageBox::warning(this, "警告", "文件夹中RAW文件不足5个");
			return;
		}

		// 只取前5个文件
		vector<Mat> rawImages;
		for (int i = 0; i < 5; ++i) {
			QFile file(fileInfoList[i].filePath());
			if (!file.open(QIODevice::ReadOnly)) {
				qWarning() << "无法打开文件:" << fileInfoList[i].filePath();
				continue;
			}

			Mat img(height, width, CV_16UC1);
			qint64 bytesRead = file.read(reinterpret_cast<char*>(img.data), width * height * 2);
			if (bytesRead != width * height * 2) {
				qWarning() << "文件大小不匹配:" << fileInfoList[i].filePath();
				continue;
			}

			rawImages.push_back(img);
			file.close();
		}

		if (rawImages.size() == 5) {
			QMessageBox::information(this, "提示", "成功加载5张RAW文件，开始BM3D处理");
			emit send_raw_5files(rawImages);
		}
		else {
			QMessageBox::warning(this, "警告", "实际成功加载的RAW文件不足5个");
		}
		});

}

opencv_raw::~opencv_raw()
{
	thread->quit();
	thread->wait(); // 等待线程结束
}

void opencv_raw::read_image(const Mat& src)
{
	// 深拷贝
	clone = src.clone();

	// 转换为QImage
	QImage qImg(clone.data, clone.cols, clone.rows, clone.step, QImage::Format_Grayscale8);
	qImg.save("9_output.png");

	// 显示在label中
	QPixmap pixmap = QPixmap::fromImage(qImg);
	if (!pixmap.isNull()) {
		QSize labelSize = ui.label->size();
		QSize scaledSize = pixmap.size().scaled(labelSize, Qt::KeepAspectRatio);
		ui.label->setPixmap(pixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
		ui.label->setAlignment(Qt::AlignCenter);
	}
}
